package com.loginregister.filter; /**
 * @author wzm
 * @create 2023-05-13 16:42
 */

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request1 = (HttpServletRequest)request;

        //登录过滤的拦截器  如果没有登录不允许进入首页或者其他后台页面

        //我们会拦截一些请求 需要条件 但是也会放行一些请求
        //定义好不需要拦截直接可以访问的路径

        String[] urls = {"/imgs/","/css/","/js/","/user/login","/user/register","/code.jpg"};

        //查看当前请求路径
        String url = request1.getRequestURL().toString();// http://localhost:8080/user/login

        System.out.println("url = " + url);
        //对比数组是否需要直接放行
        for(String s:urls){
            //对不路径中是否有需要方向的路径
            if(url.contains(s)){
                //在数组中找到了和请求路径中相同的字符串
                chain.doFilter(request, response);
                return;
            }

        }

        //不需要放行如何处理？ 肯定是不能直接放行的需要判断满不满足条件
        //代表要访问未登录不能访问的资源
        //获取登录存储的值 从登录后存储的session中获取
        Object loginUser = request1.getSession().getAttribute("loginUser");


        //判断有没有值
        if(loginUser != null) {
            //有值 访问
            chain.doFilter(request, response);
        }else {
            //无值跳转 或响应未登录结果
            request1.setAttribute("login_msg", "您尚未登录，请登录后重试！");
            request.getRequestDispatcher("/login.jsp").forward(request1,response);
        }





    }
}
